package example

import (
	"errors"
	"fmt"
	"strconv"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
	"github.com/fufuok/random"
)

func Random(a fyne.App) {
	w := a.NewWindow("hub.fastgit.org/chromedp")
	w.Resize(fyne.NewSize(900, 600))

	inputLen := widget.NewEntry()
	inputLen.SetText("20")
	output := widget.NewMultiLineEntry()
	msg := widget.NewLabel("")

	btnIntn := widget.NewButton("RandIntn", func() {
		// Instantiate *rand.Rand with the current time by default
		rd := random.NewRand()

		// Returns a new pseudo-random generator seeded with the given value.
		i, _ := strconv.Atoi(inputLen.Text)
		// random.Rand is a goroutine-safe rand.New() instance
		// FastIntn similar to rand.Intn or random.Rand.Intn, but faster.
		output.SetText(fmt.Sprint(random.Rand.Intn(i), "\n",
			random.FastIntn(i), "\n", random.FastRand(), "\n",
			rd.Int(), "\n", rd.ExpFloat64(), "\n", rd.Float32(), "\n",
			rd.Float64(), "\n", rd.Int31(), "\n",
			rd.Int31n(int32(i)), "\n", rd.Int63(), "\n", rd.Int63n(int64(i)), "\n",
			rd.NormFloat64(), "\n", rd.Perm(i), "\n", rd.Uint32(), "\n",
			rd.Uint64(), " "))
	})
	btnString := widget.NewButton("RandString", func() {
		i, _ := strconv.Atoi(inputLen.Text)
		// Fast random string generator
		output.SetText(random.RandString(i))
	})
	btnRandom := widget.NewButton("random", func() {
		i, _ := atoi2(inputLen.Text)
		output.SetText(fmt.Sprint(random.FastRandBytes(i), "\n",
			random.FastRandn(uint32(i)), "\n",
			random.RandBytes(i), "\n",
			random.RandHex(i), "\n",
			random.RandInt(0, i), "\n",
			random.RandUint32(0, uint32(i)), "\n",
		))
	})
	top := container.NewVBox(
		inputLen,  btnString, btnIntn,
		btnRandom,
	)
	c := container.NewBorder(top, msg, nil, nil, output)
	w.SetContent(c)
	w.CenterOnScreen()
	w.SetOnClosed(func() {
	})
	w.Show()
}

// https://colobu.com/2021/10/10/faster-time-parsing/
var errNotNumber = errors.New("not a valid number")

func atoi2(in string) (int, error) {
	_ = in[1]
	a, b := int(in[0]-'0'), int(in[1]-'0')
	if a < 0 || a > 9 || b < 0 || b > 9 {
		return 0, errNotNumber
	}
	return a*10 + b, nil
}
